package com.hssy.wululuaplan.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hssy.wululuaplan.entity.ClassRemain;
import com.hssy.wululuaplan.entity.DivideClass;
import com.hssy.wululuaplan.entity.Student;
import com.hssy.wululuaplan.form.DivideClassForm;
import com.hssy.wululuaplan.mapper.ClassRemainMapper;
import com.hssy.wululuaplan.mapper.DivideClassMapper;
import com.hssy.wululuaplan.mapper.StudentMapper;
import com.hssy.wululuaplan.service.DivideClassService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 班级划分 服务实现类
 * </p>
 *
 * @author Mr.Hongtao
 * @since 2024-02-28
 */
@Service
public class DivideClassServiceImpl extends ServiceImpl<DivideClassMapper, DivideClass> implements DivideClassService {

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private ClassRemainMapper classRemainMapper;

    @Override
    public List<Student> findStudentListByCourseId(Integer courseId) {
        List<DivideClass> list = baseMapper.selectList(Wrappers.<DivideClass>lambdaQuery()
                .eq(DivideClass::getCourseId, courseId));
        List<Integer> studentIdList = list.stream().map(DivideClass::getStudentId).collect(Collectors.toList());
        return studentIdList.isEmpty() ? new ArrayList<>() : studentMapper.selectBatchIds(studentIdList);
    }

    @Override
    public List<Student> filterSelectableStudents() {
        // 只有交过费的学生才能选择分班
        List<ClassRemain> list = classRemainMapper.selectList(null);
        List<Integer> studentIds = list.stream().map(ClassRemain::getStudentId).collect(Collectors.toList());
        return studentMapper.selectBatchIds(studentIds);
    }

    @Override
    @Transactional
    public void adjustClassStudents(DivideClassForm form) {
        List<Integer> studentIdList = form.getStudentIds();
        Integer courseId = form.getCourseId();
        // 删除课程下的全部学生（不管有没有）
        baseMapper.delete(Wrappers.<DivideClass>lambdaQuery()
                .eq(DivideClass::getCourseId, courseId));
        // 重新分班
        for (Integer studentId : studentIdList) {
            DivideClass entity = new DivideClass();
            entity.setStudentId(studentId);
            entity.setCourseId(courseId);
            baseMapper.insert(entity);
        }
    }
}
